using System.Web.Mvc;
using gnodotnet.Core.MailingList;
using SharpArch.Core.PersistenceSupport;
using System.Collections.Generic;
using System;
using SharpArch.Web.NHibernate;
using SharpArch.Core;
using gnodotnet.Core;
using System.Linq;
using gnodotnet.ApplicationServices;

namespace gnodotnet.Web.Controllers.MailingList
{
    [HandleError]
    public class RecipientsController : Controller
    {
        RecipientRegistration _registrationService;
        [Transaction]
        public ActionResult Subscribe(Recipient recipient) {
            _registrationService.AttemptRegistration(recipient).ProcessMessage(msg => this.SetPageMessage(msg));
            return RedirectToAction("Index", "Home");
        }
        public RecipientsController(IRepository<Recipient> recipientRepository) {
            Check.Require(recipientRepository != null, "recipientRepository may not be null");
            _registrationService = new RecipientRegistration(recipientRepository);

            this.recipientRepository = recipientRepository;
        }

        [Transaction]
        public ActionResult Index() {
            IList<Recipient> recipients = recipientRepository.GetAll();
            return View(recipients);
        }

        [Transaction]
        public ActionResult Show(int id) {
            Recipient recipient = recipientRepository.Get(id);
            return View(recipient);
        }

        public ActionResult Create() {
            RecipientFormViewModel viewModel = RecipientFormViewModel.CreateRecipientFormViewModel();
            return View(viewModel);
        }

        [ValidateAntiForgeryToken]
        [Transaction]
        [AcceptVerbs(HttpVerbs.Post)]
        public ActionResult Create(Recipient recipient) {
            if (ViewData.ModelState.IsValid && recipient.IsValid()) {
                recipientRepository.SaveOrUpdate(recipient);

                TempData[ControllerEnums.GlobalViewDataProperty.PageMessage.ToString()] = 
					"The recipient was successfully created.";
                return RedirectToAction("Index");
            }

            RecipientFormViewModel viewModel = RecipientFormViewModel.CreateRecipientFormViewModel();
            viewModel.Recipient = recipient;
            return View(viewModel);
        }

        [Transaction]
        public ActionResult Edit(int id) {
            RecipientFormViewModel viewModel = RecipientFormViewModel.CreateRecipientFormViewModel();
            viewModel.Recipient = recipientRepository.Get(id);
            return View(viewModel);
        }

        [ValidateAntiForgeryToken]
        [Transaction]
        [AcceptVerbs(HttpVerbs.Post)]
        public ActionResult Edit(Recipient recipient) {
            Recipient recipientToUpdate = recipientRepository.Get(recipient.Id);
            TransferFormValuesTo(recipientToUpdate, recipient);

            if (ViewData.ModelState.IsValid && recipient.IsValid()) {
                TempData[ControllerEnums.GlobalViewDataProperty.PageMessage.ToString()] = 
					"The recipient was successfully updated.";
                return RedirectToAction("Index");
            }
            else {
                recipientRepository.DbContext.RollbackTransaction();

				RecipientFormViewModel viewModel = RecipientFormViewModel.CreateRecipientFormViewModel();
				viewModel.Recipient = recipient;
				return View(viewModel);
            }
        }

        private void TransferFormValuesTo(Recipient recipientToUpdate, Recipient recipientFromForm) {
			recipientToUpdate.Name = recipientFromForm.Name;
			recipientToUpdate.Email = recipientFromForm.Email;
        }

        [ValidateAntiForgeryToken]
        [Transaction]
        [AcceptVerbs(HttpVerbs.Post)]
        public ActionResult Delete(int id) {
            string resultMessage = "The recipient was successfully deleted.";
            Recipient recipientToDelete = recipientRepository.Get(id);

            if (recipientToDelete != null) {
                recipientRepository.Delete(recipientToDelete);

                try {
                    recipientRepository.DbContext.CommitChanges();
                }
                catch {
                    resultMessage = "A problem was encountered preventing the recipient from being deleted. " +
						"Another item likely depends on this recipient.";
                    recipientRepository.DbContext.RollbackTransaction();
                }
            }
            else {
                resultMessage = "The recipient could not be found for deletion. It may already have been deleted.";
            }

            TempData[ControllerEnums.GlobalViewDataProperty.PageMessage.ToString()] = resultMessage;
            return RedirectToAction("Index");
        }

		/// <summary>
		/// Holds data to be passed to the Recipient form for creates and edits
		/// </summary>
        public class RecipientFormViewModel
        {
            private RecipientFormViewModel() { }

			/// <summary>
			/// Creation method for creating the view model. Services may be passed to the creation 
			/// method to instantiate items such as lists for drop down boxes.
			/// </summary>
            public static RecipientFormViewModel CreateRecipientFormViewModel() {
                RecipientFormViewModel viewModel = new RecipientFormViewModel();
                
                return viewModel;
            }

            public Recipient Recipient { get; internal set; }
        }

        private readonly IRepository<Recipient> recipientRepository;
    }
}
